package com.practice.retry;

import org.apache.log4j.Logger;

/**
 * This class provides retry mechanism for a method that throws exception.
 * And calling start method causes the task to be executed and retry when failed. 
 * @author Leonardo
 *
 */
public class VoidWithExceptionRetryWorker extends RetryWorker {

	private static final Logger logger = Logger.getLogger(VoidWithExceptionRetryWorker.class.getSimpleName());
	
	public void start(VoidWithExceptionRetryTask task, String taskDescription) {
		if (taskLogger == null) {
			taskLogger = logger;
		}
		
		if (task == null) {
			taskLogger.error("No task");
			return;
		}
		
		String failedLogFormat;
		if (taskDescription != null && !"".equals(taskDescription)) {
			failedLogFormat = "Failed: " + taskDescription + "(Exception message: %s. Retried times: %d.)";
		} else {
			failedLogFormat = "Failed. (Exception message: %s. Retried times: %d.)";
		}
		
		for (int retryCount = 0; retryCount <= maxRetryCount; retryCount++) {
			task.setRetriedTimes(retryCount);
			
			try {
				task.run();
				task.setSuccess(true);
				break;
			} catch (Exception ex) {
				logger.error(String.format(failedLogFormat, ex.getMessage(), retryCount));
				logger.error(ex.getStackTrace());
				
				if (retryCount < maxRetryCount) {
					try {
						Thread.sleep(sleepMilliseconds);
					} catch (InterruptedException interruptedEx){
						logger.error("Sleep before retry failed.", interruptedEx);
					}
				} else {
					task.setSuccess(false);
				}
			}
		}
	}
}
